﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.Extensions.DependencyInjection;
using Serilog.Events;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using WatchDog;
using WatchDog.WatchItemManages;

namespace WatchDogApp.Windows
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow
    {


        public MainWindow()
        {
            InitializeComponent();


            this.comboBox1.Items.Add("生产模式");
            this.comboBox1.Items.Add("调试模式");
            this.comboBox1.SelectedItem = "生产模式";
            this.comboBox1.SelectionChanged += (s, e) =>
            {
                if (this.comboBox1.SelectedItem.ToString() == "调试模式")
                {
                    SerilogHelper.LevelSwitch.MinimumLevel = LogEventLevel.Debug;
                    WindowsServiceManage.ExecuteCommand(ZWatchDogServiceManage.serviceName, WindowsServiceCustomCommands.ServiceLogLevelDebug);
                }
                else
                {
                    SerilogHelper.LevelSwitch.MinimumLevel = LogEventLevel.Warning;
                    WindowsServiceManage.ExecuteCommand(ZWatchDogServiceManage.serviceName, WindowsServiceCustomCommands.ServiceLogLevelWarning);
                }
            };



            var _vm = App.Current.Service.GetRequiredService<MainWindowViewModel>();

            _vm.ServiceStatus = "状态：" + ZWatchDogServiceManage.GetStatus();


            this.IsVisibleChanged += (s, e) =>
            {
                if (this.IsVisible)
                    _vm.Start();
                else
                    _vm.Stop();
            };
            this.DataContext = _vm;

            //this.dataGrid.SelectionChanged += (s, e) =>
            //{
            //    if (e.AddedItems.Count == 1)
            //    {
            //        var item = e.AddedItems[0] as WatchItemDto;

            //        var see = item;
            //    }
            //    //var ss = s;
            //    //var ee = e;
            //};
            this.Closing += OnClosing;
        }

        /// <summary>
        /// Save session data on closing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                e.Cancel = true;

                this.Hide();
            }
            catch (Exception exp)
            {
                Debug.WriteLine(exp);
            }
        }


        public static LogWindow _logWindow = null;
        private void onClick(object sender, RoutedEventArgs e)
        {
            if (_logWindow == null)
            {
                _logWindow = new LogWindow();
                _logWindow.Show();
                _logWindow.Closed += OnClosed;
            }
            else
            {
                if (_logWindow.IsActive == false)
                {
                    _logWindow.Activate();
                }
            }
        }

        private void OnClosed(object sender, EventArgs e)
        {
            _logWindow = null;
        }

         
    }

    public class MainWindowViewModel : ObservableObject
    {
        private readonly System.Timers.Timer _timer;
        //private readonly WatchItemManage _watchItemManage { get; set; }

        public MainWindowViewModel()
        {
            _timer = new System.Timers.Timer(1000) { AutoReset = true };
            _timer.Elapsed += (sender, eventArgs) =>
            {
                NowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                UpdateDataList();

                ServiceController service = new ServiceController("W32Time");
                if (service.Status != ServiceControllerStatus.Running)
                {
                    W32TimeServiceStstus = "系统时间同步服务未开启";
                }
                else
                {
                    W32TimeServiceStstus = "系统时间同步服务已开启";
                }
            };

            AddCommand = new RelayCommand(() =>
            {
                var mainWindow = App.Current.Service.GetRequiredService<MainWindow>();

                var settingsWindow = new SettingsWindow();
                //在屏幕中间显示
                //settingsWindow.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                //在父窗口中间显示，
                settingsWindow.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
                settingsWindow.Owner = mainWindow;

                //settingsWindow.WindowStartupLocation = System.Windows.WindowStartupLocation.Manual;
                //settingsWindow.Left = 0;
                //settingsWindow.Top = 0;
                settingsWindow.ShowDialog();
            });
            EditCommand = new RelayCommand(() =>
            {
                if (this.SelectedItem == null)
                {
                    HandyControl.Controls.MessageBox.Info("请选择要编辑的数据行");
                }
                else
                {
                    var mainWindow = App.Current.Service.GetRequiredService<MainWindow>();
                    var _watchItemManage = App.Current.Service.GetRequiredService<WatchItemManage>();

                    var model = _watchItemManage.GetAllWatchItems().FirstOrDefault(c => c.Id == this.SelectedItem.Id);
                    if (model != null)
                    {
                        var settingsWindow = new SettingsWindow(new EditWatchItemDto()
                        {
                            Id = this.SelectedItem.Id,
                            FilePath = this.SelectedItem.FilePath,
                            Name = this.SelectedItem.Name,
                            AutoStart = model.AutoStart,
                            DelayStartInSecond = model.DelayStart,
                            RestartIntervalInHour = model.ScheduledRestart / 60,
                            Remark = model.Remark
                        });

                        settingsWindow.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
                        settingsWindow.Owner = mainWindow;

                        settingsWindow.ShowDialog();
                    }


                }

            });
            DelCommand = new RelayCommand(() =>
            {
                if (this.SelectedItem == null)
                {
                    HandyControl.Controls.MessageBox.Info("请选择要删除的数据行");
                }
                else
                {
                    if (HandyControl.Controls.MessageBox.Ask("确定要删除 " + this.SelectedItem.Name + " 吗？", "删除数据") == System.Windows.MessageBoxResult.OK)
                    {
                        var _watchItemManage = App.Current.Service.GetRequiredService<WatchItemManage>();
                        _watchItemManage.Del(this.SelectedItem.Id);
                        DataList.Remove(this.SelectedItem);
                    }

                }
            });

            StopCommand = new RelayCommand(() =>
            {
                if (this.SelectedItem == null)
                {
                    HandyControl.Controls.MessageBox.Info("请选择要停止的数据行");
                }
                else
                {
                    if (HandyControl.Controls.MessageBox.Ask("确定要停止 " + this.SelectedItem.Name + " 吗？", "停止") == System.Windows.MessageBoxResult.OK)
                    {
                        var _watchItemManage = App.Current.Service.GetRequiredService<WatchItemManage>();
                        _watchItemManage.Update(this.SelectedItem.Id, false);
                        ProcessHelper.Stop(this.SelectedItem.FilePath);
                        UpdateDataList();
                    }
                }
            });
            StartCommand = new RelayCommand(() =>
            {
                if (this.SelectedItem == null)
                {
                    HandyControl.Controls.MessageBox.Info("请选择要启动或重新启动的数据行");
                }
                else
                {
                    if (HandyControl.Controls.MessageBox.Ask("确定要启动/重新启动 " + this.SelectedItem.Name + " 吗？", "启动") == System.Windows.MessageBoxResult.OK)
                    {
                        ProcessHelper.Stop(this.SelectedItem.FilePath);
                        ProcessHelper.Start(this.SelectedItem.FilePath);
                        UpdateDataList();
                    }
                }
            });
            SwitchCommand = new RelayCommand(() =>
            {
                if (this.SelectedItem == null)
                {
                    HandyControl.Controls.MessageBox.Info("请选择要切换自动启动的数据行");
                }
                else
                {
                    var _watchItemManage = App.Current.Service.GetRequiredService<WatchItemManage>();
                    _watchItemManage.Update(SelectedItem.Id, SelectedItem.AutoStart);
                    UpdateDataList();
                }
            });
        }
        public void Start() => _timer.Start();
        public void Stop() => _timer.Stop();

        public ObservableCollection<DataListViewModel> DataList { get; set; } = new ObservableCollection<DataListViewModel>();

        private DataListViewModel _selectedItem;
        public DataListViewModel SelectedItem
        {
            get => _selectedItem;
            set
            {
                var u = value;
                _selectedItem = u;
            }
        }
        private int _selectedIndex;
        public int SelectedIndex
        {
            get => _selectedIndex;
            set => SetProperty(ref _selectedIndex, value);
        }


        //private IList<WatchItemDto> _dataList = new List<WatchItemDto>();
        //public IList<WatchItemDto> DataList
        //{
        //    get => _dataList;
        //    set => SetProperty(ref _dataList, value);
        //}

        //private bool isDubug = false;
        //public bool IsDubug {
        //    get => isDubug;
        //    set => SetProperty(ref isDubug, value);
        //}    

        private string nowTime = string.Empty;
        public string NowTime
        {
            get => nowTime;
            set => SetProperty(ref nowTime, value);
        }


        private string status = string.Empty;
        public string ServiceStatus
        {
            get => status;
            set => SetProperty(ref status, value);
        }

        private string ststus2 = string.Empty;
        public string W32TimeServiceStstus
        {
            get => ststus2;
            set => SetProperty(ref ststus2, value);
        }
        public ICommand AddCommand { get; }
        public ICommand EditCommand { get; }
        public ICommand DelCommand { get; }
        public ICommand StartCommand { get; }
        public ICommand StopCommand { get; }
        public ICommand SwitchCommand { get; }


        public void UpdateDataList()
        {
            System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.
                DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
            System.Threading.SynchronizationContext.Current.Post(pl =>
            {
                var _watchItemManage = App.Current.Service.GetRequiredService<WatchItemManage>();
                var data = _watchItemManage.GetAllWatchItems();
                //var data = new List<WatchItem>();
                //for (int i = 0; i < 50; i++)
                //{
                //    data.Add(new WatchItem()
                //    {
                //        Id = i,
                //        AutoStart = true,
                //        DelayStart = 5,
                //        DisplayName = "text" + i,
                //        FileName = "text" + i,
                //        FilePath = DateTime.Now.ToString(),
                //        Remark = "",
                //        ScheduledRestart = 0
                //    });
                //}

                //DataList.Clear();
                foreach (var item in data)
                {
                    bool add = false;
                    for (int i = 0; i < DataList.Count; i++)
                    {
                        if (DataList[i].Id == item.Id)
                        {
                            int aa = (int)Math.Ceiling(item.ScheduledRestart / 60.0);
                            if (DataList[i].Name != item.DisplayName)
                                DataList[i].Name = item.DisplayName;
                            if (DataList[i].FilePath != item.FilePath)
                                DataList[i].FilePath = item.FilePath;
                            if (DataList[i].AutoStart != item.AutoStart)
                                DataList[i].AutoStart = item.AutoStart;
                            if (DataList[i].RestartIntervalInHour != (aa == 0 ? "-" : aa.ToString()))
                                DataList[i].RestartIntervalInHour = aa == 0 ? "-" : aa.ToString();
                            DataList[i].DurationInMinute = ProcessHelper.GetRunningTotalMinutes(item.FilePath).ToString("F2");
                            DataList[i].Status = ProcessHelper.IsRuning(item.FilePath) ? "运行中" : "未运行";
                            add = true;
                        }
                    }
                    if (!add)
                    {
                        int aa = (int)Math.Ceiling(item.ScheduledRestart / 60.0);
                        DataList.Add(new DataListViewModel()
                        {
                            Id = item.Id,
                            Name = item.DisplayName,
                            FilePath = item.FilePath,
                            AutoStart = item.AutoStart,
                            RestartIntervalInHour = aa == 0 ? "-" : aa.ToString(),
                            DurationInMinute = ProcessHelper.GetRunningTotalMinutes(item.FilePath).ToString("F2"),
                            Status = ProcessHelper.IsRuning(item.FilePath) ? "运行中" : "未运行",
                        });
                    }
                }

                //SelectedIndex = 2;
                //SelectedItem = DataList[2];

                //DataList.Insert(0,new WatchItemDto());
                //DataList.RemoveAt(0);
            }, null);



        }
    }
    public partial class DataListViewModel : ObservableObject
    {
        [ObservableProperty]
        public int id = 0;

        [ObservableProperty]
        public string name = string.Empty;
        [ObservableProperty]
        public string status = string.Empty;
        [ObservableProperty]
        public string durationInMinute = string.Empty;

        [ObservableProperty]
        public string restartIntervalInHour = string.Empty;
        [ObservableProperty]
        public bool autoStart;
        [ObservableProperty]
        public string filePath = string.Empty;
        [ObservableProperty]
        public bool isSelected;
    }
}
